import classNames from 'classnames'
import { useEffect, useRef, useState } from 'react'
import CountUp from 'react-countup'

import type { IDistrictRankItemRender } from '../../AdministrativeAreaRanking'

import './index.less'

export interface RankDataItemProps extends IDistrictRankItemRender {
  rankMaxAverage: number
  rankDataIndex: number
}

function RankDataItem(props: RankDataItemProps) {
  const {
    regionCode,
    regionName,
    average,
    prevAverage,
    prevMaxVverage,
    rankMaxAverage,
    rankDataIndex
  } = props
  const intervalIdRef = useRef<any>()
  const [proInnerWidthPercent, setProInnerWidthPercent] = useState<number>(0)

  useEffect(() => {
    if (!rankMaxAverage) {
      setProInnerWidthPercent(0)
      return
    }
    let prevPercent = 0
    if (!prevMaxVverage) {
      prevPercent = 0
    } else {
      prevPercent = Math.ceil((prevAverage / prevMaxVverage) * 100)
    }
    const currPercent = Math.ceil((average / rankMaxAverage) * 100)

    if (currPercent === prevPercent) {
      setProInnerWidthPercent(currPercent)
      return
    }
    const everyPill = (currPercent - prevPercent) / 10

    let startPercent = prevPercent
    let recursionCount = 10

    //2000   200(interval最短200ms)
    intervalIdRef.current = setInterval(() => {
      if (recursionCount <= 0) {
        clearInterval(intervalIdRef.current)
        return
      }
      startPercent += everyPill
      setProInnerWidthPercent(startPercent)
      recursionCount--
      // console.log('--recursionCount--:', recursionCount);
    }, 200)

    return () => {
      if (intervalIdRef.current) {
        clearInterval(intervalIdRef.current)
      }
    }
  }, [average, rankDataIndex, rankMaxAverage])

  return (
    <div className="bigscreen-gover-center-district-data-item">
      <div className="item-summary">
        <p
          className={classNames('summary-index', { ['no-data']: !regionName })}
        >
          {rankDataIndex + 1}
        </p>
        <p className="summary-name">
          <span className="name-text">{regionName}</span>
        </p>
        <p
          className={classNames('summary-count', { ['no-data']: !regionName })}
        >
          <CountUp start={prevAverage} end={average} duration={2} />
        </p>
      </div>
      <div className="item-progress">
        <div
          className="progress-inner"
          style={{
            width: `${proInnerWidthPercent}%`,
            background:
              'linear-gradient( 90deg, rgba(246,110,44,0.6) 0%, #F66E2C 100%)'
          }}
        ></div>
      </div>
    </div>
  )
}

export default RankDataItem
